package org.ourguy.mymoviesandshows;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.ourguy.mymoviesandshows.broadcastreceivers.AlarmBroadcastReceiver;
import org.ourguy.mymoviesandshows.datamodel.Episode;
import org.ourguy.mymoviesandshows.datamodel.ITitle;
import org.ourguy.mymoviesandshows.datamodel.Series;
import org.ourguy.mymoviesandshows.managers.DataAccessException;
import org.ourguy.mymoviesandshows.managers.DataAccessManager;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.IBinder;
import android.util.Log;

public class ReminderService extends Service {
	/**
	 * The sleep time of the thread after failure of data retrieval.
	 */
	private static final long DELAY = 30 * 1000;
	
	/**
	 * The sleep time of the thread after failure of data retrieval.
	 */
	private static final long PERIOD = 6 * 60 * 60 * 1000; //6 * 60 * 60 * 1000;
	
	/**
	 * The log tag for this service
	 */
	private static final String LOGTAG = "ReminderService";
	
	/**
	 * The delay timer itself
	 */
	private Timer timer = null;
	
	/**
	 * 
	 */
	private RefreshTask task;
	
	private ArrayList<PendingIntent> notifications =
			new ArrayList<PendingIntent>();
	
	/**
	 * The refresher background thread
	 */
	private class RefreshTask extends TimerTask {
		private Intent getIntentFor(Episode ep, Series series) {
	    	Intent intent = 
	    			new Intent(ReminderService.this, AlarmBroadcastReceiver.class);
	    	intent.setAction("org.ourguy.mymoviesandshows.broadcastreceivers.ALARM");
	    	intent.putExtra("show", series.getApiId());
	    	intent.putExtra("season", ep.getSeasonNumber());
	    	intent.putExtra("episode", ep.getNumber());
	    	intent.putExtra("seriesTitle", series.getTitle());
	    	intent.putExtra("episodeTitle", ep.getTitle());
	    	intent.putExtra("episodeId", ep.hashCode());
	    	intent.putExtra("airTime", ep.getFirstAired().getTime());
			return intent;
		}
		
		private PendingIntent getAlarmFor(Episode ep, Series series) {
			Intent intent = getIntentFor(ep, series);
			PendingIntent pendingIntent =
					PendingIntent.getBroadcast(ReminderService.this, ep.hashCode(), intent,
							PendingIntent.FLAG_ONE_SHOT);
			return pendingIntent;
		}
		
		@Override
		public void run() {
			Log.i(LOGTAG, "RefreshTask is running...");
			ConnectivityManager cm = (ConnectivityManager) getSystemService(
					Context.CONNECTIVITY_SERVICE);
			
			if (cm.getActiveNetworkInfo().isConnectedOrConnecting()) {
				Log.i(LOGTAG, "RefreshTask is refreshing...");
				
				AlarmManager am =
						(AlarmManager) getSystemService(Context.ALARM_SERVICE);
				
				DataAccessManager dam =
						DataAccessManager.getInstance(ReminderService.this);
				
				Log.i(LOGTAG, "Canceling all notifications...");
				for (PendingIntent operation: notifications)
					am.cancel(operation);
				
				Log.i(LOGTAG, "Getting list of favourites...");
				ArrayList<ITitle> favs = dam.getFavorites();
				Log.i(LOGTAG, "The favs are " + favs.size());
				for(ITitle fav: favs) {
					Log.i(LOGTAG, "Looking at " + fav.getTitle());
					try {
						if(fav instanceof Series) {
							Log.i(LOGTAG, fav.getTitle() + " is a TV Show!");
							Series series = (Series)fav;
							ArrayList<Episode> upcoming =
									dam.getUpComing(series);
							for(Episode ep: upcoming) {
								PendingIntent notification =
										getAlarmFor(ep, series);
								
								notifications.add(notification);
								Log.i(LOGTAG, "Adding reminder for "+
										fav.getTitle()+" ep " + ep.getNumber()
										+ "" + ep.getFirstAired());
								am.set(AlarmManager.RTC_WAKEUP,
										ep.getFirstAired().getTime() 
										+ series.getReminderOffset(),
										notification);
							}
						}
					} catch (DataAccessException e) {
						Log.i(LOGTAG, "Data access exception...");
					}
				}
			} else {
				Log.i(LOGTAG, "Can't refresh - no connectivity...");
			}
		}
	}

	@Override
	public void onCreate() {
		super.onCreate();
//		android.os.Debug.waitForDebugger();
		Log.i(LOGTAG, "created");
	}
	
	@Override
	public void onStart(final Intent intent, final int startId) {
		super.onStart(intent, startId);
		Log.i(LOGTAG, "starting");
		if (timer == null) {
			timer = new Timer();
			task = new RefreshTask();
			timer.schedule(task, DELAY, PERIOD);
			Log.i(LOGTAG, "started");
		} else {
			Log.i(LOGTAG, "already running");
		}
	}

    
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
}
